import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Form, Input, Modal, Space, Tag, message } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import axios from 'axios';

const Admin = () => {
  const [boxes, setBoxes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBox, setEditingBox] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchBoxes();
  }, []);

  const fetchBoxes = async () => {
    setLoading(true);
    try {
      const response = await axios.get('http://localhost:3001/api/admin/boxes');
      setBoxes(response.data.boxes);
    } catch (error) {
      message.error('获取检测盒失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record) => {
    setEditingBox(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (record) => {
    try {
      await axios.delete(`http://localhost:3001/api/admin/results/${record.id}`);
      message.success('删除成功');
      fetchBoxes();
    } catch (error) {
      message.error('删除失败：' + error.message);
    }
  };

  const handleSubmit = async (values) => {
    try {
      const url = editingBox 
        ? `http://localhost:3001/api/admin/boxes/${editingBox.box_id}`
        : 'http://localhost:3001/api/tests/bind';
      
      const method = editingBox ? 'put' : 'post';
      
      await axios[method](url, {
        ...values,
        boxId: editingBox ? editingBox.box_id : values.boxId
      });
      
      message.success(editingBox ? '更新成功' : '添加成功');
      setModalVisible(false);
      fetchBoxes();
      form.resetFields();
    } catch (error) {
      message.error('操作失败：' + error.message);
    }
  };

  const columns = [
    {
      title: '检测盒ID',
      dataIndex: 'box_id',
      key: 'box_id',
    },
    {
      title: '批次号',
      dataIndex: 'batch_number',
      key: 'batch_number',
    },
    {
      title: '固件版本',
      dataIndex: 'firmware_version',
      key: 'firmware_version',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '活跃' : '待处理'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card 
        title="检测盒管理" 
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingBox(null);
                form.resetFields();
                setModalVisible(true);
              }}
            >
              添加检测盒
            </Button>
            <Button onClick={fetchBoxes}>
              刷新
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={boxes}
          loading={loading}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingBox ? '编辑检测盒' : '添加检测盒'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          {!editingBox && (
            <Form.Item
              label="检测盒ID"
              name="boxId"
              rules={[{ required: true, message: '请输入检测盒ID' }]}
            >
              <Input placeholder="请输入检测盒ID" />
            </Form.Item>
          )}
          
          <Form.Item
            label="批次号"
            name="batchNumber"
            rules={[{ required: true, message: '请输入批次号' }]}
          >
            <Input placeholder="请输入批次号" />
          </Form.Item>
          
          <Form.Item
            label="固件版本"
            name="firmwareVersion"
            rules={[{ required: true, message: '请输入固件版本' }]}
          >
            <Input placeholder="例如：v2.1.0" />
          </Form.Item>
          
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Input placeholder="active 或 pending" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Admin;